import React from "react";
import ReactDOM from "react-dom";
// 实现useState, 修复使用多次useState出现的问题
// 通过定义个数组对象，以及stateIndex索引，每次调用useState都把索引增加，可以进行区别不同的useState
/* useState实现 */
let lastStates = [];
let stateIndex = 0;
function useState(initialState) {
  lastStates[stateIndex] = lastStates[stateIndex] || initialState;
  let currentIndex = stateIndex;
  function setState(newState) {
    lastStates[currentIndex] = newState;
    render();
    stateIndex = 0;
  }
  return [lastStates[stateIndex++], setState];
}
/* useContext实现 */
function useContext(context) {
  return context._currentValue;
}
const CounterCtx = React.createContext();
function App() {
  let [state, setState] = useState({ number: 0 });
  return (
    <CounterCtx.Provider value={{ state, setState }}>
      <div>
        {/* 这里可以是多层组件的子组件 */}
        <Counter />
      </div>
    </CounterCtx.Provider>
  );
}
function Counter() {
  let { state, setState } = useContext(CounterCtx);
  return (
    <div>
      <p>{state.number}</p>
      <button onClick={() => setState({ number: state.number + 1 })}>+</button>
      <button onClick={() => setState({ number: state.number - 1 })}>-</button>
    </div>
  );
}
function render() {
  ReactDOM.render(<App />, document.getElementById("root"));
}
render();